#include <thread>
#include <iostream>
#include <mutex>

using std::cout;
using std::endl;

std::timed_mutex mutex;

void fireworks()
{
    //waiting to get a lock: each trhead prints "-" every 200ms
    while(!mutex.try_lock_for(std::chrono::milliseconds(200)))  //如果 timed_mutex 当前未被任何线程锁定，则调用线程将其锁定（从此时开始，直到调用其成员 unlock，该线程拥有 timed_mutex）。
    {
        cout << "-"; //每个线程都会打印的
    }


    cout << std::this_thread::get_id();
    //got a lock ! - wait for 1s ,the this thread prints "*"
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    cout << "*\n";
    mutex.unlock();
}

int main(void)
{
    std::thread threads[10];

    for(int i = 0; i < 10; ++i)
    {
        threads[i] = std::thread(fireworks);
    }

    for(auto & th : threads)
    {
        th.join();
    }
    return 0;
}
